package com.yayako.modules.user.service;

import com.yayako.modules.department.mapper.DepartmentMapper;
import com.yayako.modules.user.entity.User;
import com.yayako.modules.user.mapper.UserMapper;
import com.yayako.result.Result;
import com.yayako.result.ResultCode;
import com.yayako.result.ResultFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/** @author cyy */
@Service
public class UserService implements UserDetailsService {
  @Autowired UserMapper userMapper;
  @Autowired DepartmentMapper departmentMapper;

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    return userMapper.selectByUserName(s);
  }

  public Result register(User user) {
    Result result;
    user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
    try {
      userMapper.insert(user);
      result = ResultFactory.bulidSuccessResult("注册成功！");
    } catch (DataAccessException e) {
      result = ResultFactory.buildResult(ResultCode.INTERNAL_SERVER_ERROR, "注册失败，该用户名已存在！", e);
      throw e;
    }
    return result;
  }

  public List<User> getData() {
    return userMapper.getData();
  }

  public Result edit(User user) {
    Result result;
    user.setDept(departmentMapper.getDeptByName(user.getDept().getName()));
    try {
      userMapper.updateByPrimaryKey(user);
      result = ResultFactory.bulidSuccessResult(null);
    } catch (DataAccessException e) {
      result = ResultFactory.buildResult(ResultCode.INTERNAL_SERVER_ERROR, "修改失败！", e);
      throw e;
    }
    return result;
  }

  public Result delete(String id) {
    Result result;
    try {
      userMapper.deleteByPrimaryKey(id);
      result = ResultFactory.bulidSuccessResult(null);
    } catch (DataAccessException e) {
      result = ResultFactory.buildResult(ResultCode.INTERNAL_SERVER_ERROR, "删除失败！", e);
      throw e;
    }
    return result;
  }

  public Result upload(List<Object> list) {
    Result result;
    int successNum = 0;
    int failNum = 0;
    for (Object user : list) {
      //      try {
      //        userMapper.insert((User) user);
      //        successNum++;
      //      } catch (DataAccessException e) {
      //        failNum++;
      //      }
      System.out.println((User) user);
    }
    result =
        ResultFactory.buildResult(
            ResultCode.INTERNAL_SERVER_ERROR,
            "导入成功" + successNum + "条\n导入失败" + failNum + "条",
            null);
    return null;
  }

  public void bulkInsert(List<Object> userList) {
    userMapper.bulkInsert(userList);
  }
}
